package com.wstuo.common.security.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.wstuo.common.bpm.api.IBPS;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.dao.ICompanyDAO;
import com.wstuo.common.security.dao.ICustomerDAO;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IOrganizationInnerDAO;
import com.wstuo.common.security.dao.IOrganizationServicesDAO;
import com.wstuo.common.security.dao.IRoleDAO;
import com.wstuo.common.security.dao.IServiceTimeDAO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.dto.OrganizationDTO;
import com.wstuo.common.security.dto.OrganizationGridDTO;
import com.wstuo.common.security.dto.OrganizationQueryDTO;
import com.wstuo.common.security.dto.OrganizationTreeDTO;
import com.wstuo.common.security.entity.Company;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.OrganizationInner;
import com.wstuo.common.security.entity.OrganizationServices;
import com.wstuo.common.security.entity.Role;
import com.wstuo.common.security.entity.ServiceTime;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.enums.SessionName;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.util.AppliactionBaseListener;

/**
 * 机构业务
 */
@SuppressWarnings("unchecked")
public class OrganizationService implements IOrganizationService {
	private static final Logger LOGGER = Logger.getLogger(OrganizationService.class );
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private ICompanyDAO companyDAO;
	@Autowired
	private IOrganizationInnerDAO organizationInnerDAO;
	@Autowired
	private ICustomerDAO customerDAO;
	@Autowired
	private IOrganizationServicesDAO organizationServicesDAO;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private IRoleDAO roleDAO;
	@Autowired
	private IServiceTimeDAO serviceTimeDAO;
	@Autowired
	private AppContext appctx;
	@Autowired
	private IMyAllCustomerCompanys myAllCustomerCompanys;

	/**
     * 分页查询机构信息.
     * @param organizationQueryDTO 分页查询数据DTO：OrganizationQueryDTO
     * @return 分页数据：PageDTO
     */
	@Transactional()
	public PageDTO findPagerOrganization(OrganizationQueryDTO organizationQueryDTO) {
		PageDTO p = organizationDAO.findPager(organizationQueryDTO);
		List<Organization> entities = (List<Organization>) p.getData();
		List<OrganizationGridDTO> dtos = new ArrayList<OrganizationGridDTO>();

		for (Organization entity : entities) {
			OrganizationGridDTO dto = new OrganizationGridDTO();
			OrganizationGridDTO.entity2dto(entity, dto);
			if (entity.getParentOrg() != null) {
				dto.setParentOrgName(entity.getParentOrg().getOrgName());
				dto.setParentNo(entity.getParentOrg().getOrgNo());
			}
			if (entity.getPersonInCharge() != null) {
				dto.setPersonInChargeNo(entity.getPersonInCharge().getUserId());
				dto.setPersonInChargeName(entity.getPersonInCharge()
						.getFullName());
			}
			dto.setOrgType(entity.getOrgType());
			// 添加
			dtos.add(dto);
		}
		p.setData(dtos);
		return p;
	}

	/**
	 * 根据公司编号，递归获取所有子机构编号.
	 * @param subIds
	 * @param orgNo
	 */
	private void findAllSubOrganizationByOrganizationNo(List<Long> subIds,Long orgNo) {

		subIds.add(orgNo);

		Organization org = organizationDAO.findById(orgNo);

		if (org != null && org.getSuborgs() != null
				&& org.getSuborgs().size() > 0) {

			for (Organization o : org.getSuborgs()) {

				if (o.getDataFlag() != 99) {
					findAllSubOrganizationByOrganizationNo(subIds, o.getOrgNo());
				}

			}
		}
	}

	/**
     * 根据ID数组分页查找机构.
     * @param organizationQueryDTO 分页查询DTO：OrganizationQueryDTO
     * @return 分页数据：PageDTO
     */
	@Transactional()
	public PageDTO findPagerOrganizationByIds(OrganizationQueryDTO organizationQueryDTO) {
		PageDTO p = organizationDAO.findPagerByIds(organizationQueryDTO);
		List<Organization> entities = (List<Organization>) p.getData();
		List<OrganizationGridDTO> dtos = new ArrayList<OrganizationGridDTO>();

		for (Organization entity : entities) {
			OrganizationGridDTO dto = new OrganizationGridDTO();
			OrganizationGridDTO.entity2dto(entity, dto);

			if (organizationInnerDAO.findById(entity.getOrgNo()) != null) {
				dto.setOrgType("organization");
			}

			if (companyDAO.findById(entity.getOrgNo()) != null) {
				dto.setOrgType("company");
			}

			if (organizationServicesDAO.findById(entity.getOrgNo()) != null) {
				dto.setOrgType("services");
			}

			if (entity.getParentOrg() != null) {
				dto.setParentOrgName(entity.getParentOrg().getOrgName());
				dto.setParentNo(entity.getParentOrg().getOrgNo());
			}

			if (entity.getPersonInCharge() != null) {
				dto.setPersonInChargeNo(entity.getPersonInCharge().getUserId());
				dto.setPersonInChargeName(entity.getPersonInCharge()
						.getLoginName());
			}

			// 查找类型
			dtos.add(dto);
		}

		p.setData(dtos);

		return p;
	}

	/**
     * 查找服务机构.
     * @return 机构DTO集合：List<OrganizationDTO>
     */
	@Transactional()
	public List<OrganizationDTO> findAllOrganization() {
		List<Organization> entities = organizationDAO.findAll();
		List<OrganizationDTO> dtos = new ArrayList<OrganizationDTO>();

		for (Organization entity : entities) {
			OrganizationDTO dto = new OrganizationDTO();

			OrganizationDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
     * 根据编号查找机构信息.
     * @param orgNo 机构编号：Long orgNo
     * @return 机构数据：OrganizationDTO
     */
	public OrganizationDTO findOrganizationById(Long orgNo) {
		OrganizationDTO dto = new OrganizationDTO();
		Organization entity = organizationDAO.findById(orgNo);

		OrganizationDTO.entity2dto(entity, dto);

		return dto;
	}

	/**
     * 查找服务机构（树形）.
     * @param companyNo
     * @return 树形集合：List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findOrgTreeDtos(Long companyNo) {

		List<Company> companys = new ArrayList<Company>();

		if (companyNo != null && companyNo != -1) {
			companys.add(companyDAO.findById(companyNo));
		} else {
			companys.addAll(companyDAO.findAll());
		}

		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();

		for (Company c : companys) {
			if(!StringUtils.hasText(c.getPath())){
				List<Organization> orgs = organizationDAO.findAll();
				for(Organization org : orgs){
					if(org.getParentOrg()!=null){
						org.setPath(org.getParentOrg().getPath()+org.getOrgNo()+"/");
					}else{
						org.setPath(org.getOrgNo()+"/");
					}
				}
			}
			OrganizationTreeDTO dto = new OrganizationTreeDTO();
			company2dto(c, dto);
			dtos.add(dto);
		}

		return dtos;
	}
	
	
	/**
     * 查找登陆用户负责的服务机构（树形）.
     * @param companyNo
     * @return 树形集合：List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findOrgTreeDtosByUser(Long companyNo) {

		List<Company> companys = new ArrayList<Company>();

		if (companyNo != null && companyNo != -1) {
			companys.add(companyDAO.findById(companyNo));
		} else {
			String loginName = appctx.getCurrentLoginName();
			companys.addAll(myAllCustomerCompanys.findCompanysMyAllCustomer(loginName));
		}

		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();

		for (Company c : companys) {
			if(!StringUtils.hasText(c.getPath())){
				List<Organization> orgs = organizationDAO.findAll();
				for(Organization org : orgs){
					if(org.getParentOrg()!=null){
						org.setPath(org.getParentOrg().getPath()+org.getOrgNo()+"/");
					}else{
						org.setPath(org.getOrgNo()+"/");
					}
				}
			}
			OrganizationTreeDTO dto = new OrganizationTreeDTO();
			company2dto(c, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
     * 根据父机构ID查子机构树结构数据
     * @param parentOrgNo
     * @return List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findSubOrgTreeDtos(Long parentOrgNo) {

		List<Organization> orgs = organizationDAO.findSubOrg(parentOrgNo);

		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();

		for (Organization org : orgs) {

			OrganizationTreeDTO dto = new OrganizationTreeDTO();
			copyValue(org, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
     * 查找内部机构树
     * @return 树形集合：List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findInnerOrgTreeDtos() {
		List<Company> entities = companyDAO.findATree();

		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();

		for (Company entity : entities) {
			List<OrganizationInner> organizationInners = organizationInnerDAO
					.findByCompany(entity.getOrgNo());

			if (!organizationInners.isEmpty()) {
				for (OrganizationInner inner : organizationInners) {
					OrganizationTreeDTO dto = new OrganizationTreeDTO();

					tree2DTO(inner, dto);

					dtos.add(dto);
				}
			}
		}

		return dtos;
	}

	/**
     * 查找服务机构树
     * @return 树形集合：List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findServicesOrgTreeDtos() {
		List<Company> entities = companyDAO.findATree();

		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();

		for (Company entity : entities) {
			List<OrganizationServices> organizationServices = organizationServicesDAO
					.findByCompany(entity.getOrgNo());

			if (!organizationServices.isEmpty()) {
				for (OrganizationServices ser : organizationServices) {
					OrganizationTreeDTO serData = new OrganizationTreeDTO();
					tree2DTO(ser, serData);
					dtos.add(serData);
				}
			}
		}

		return dtos;
	}

	/**
     * 查找选择机构树
     * @return 树形集合：List<OrganizationTreeDTO>
     */
	@Transactional
	public List<OrganizationTreeDTO> findOrganizationSelectTree() {

		List<Company> entities = companyDAO.findATree();
		List<OrganizationTreeDTO> dtos = new ArrayList<OrganizationTreeDTO>();
		for (Company entity : entities) {
			OrganizationTreeDTO dto = new OrganizationTreeDTO();
			tree2DTO(entity, dto);
			dtos.add(dto);
		}
		return dtos;
	}

	/**
	 * company2dto 树形递归
	 * 
	 * @param company
	 * @param dto
	 */
	@Transactional
	private void company2dto(Company company, OrganizationTreeDTO dto) {
		try {

			// 赋值
			copyValue(company, dto);

			if (company.getOrgType().equals("itsop")) {// 外包客户视图（无内部或服务部门）

				// fill innerOrgs
				List<OrganizationInner> organizationInners = organizationInnerDAO
						.findByCompany(company.getOrgNo());

				if (!organizationInners.isEmpty()) {
					dto.setState("open");
					for (OrganizationInner inner : organizationInners) {
						OrganizationTreeDTO innerData = new OrganizationTreeDTO();
						tree2DTO(inner, innerData);
						dto.getChildren().add(innerData);
					}
				}

			} else {// 非外包商视图

				// innerOrgs
				OrganizationTreeDTO innerPanel = new OrganizationTreeDTO();
				LanguageContent l = LanguageContent.getInstance();
				innerPanel.setData(l
						.getContent("OrganizationService.company2dto.Data"));
				innerPanel.getAttr().put("orgName",
						l.getContent("OrganizationService.company2dto.Data"));
				innerPanel.getAttr().put("companyNo",
						company.getOrgNo().toString());
				innerPanel.getAttr().put("orgType", "innerPanel");
				innerPanel.getAttr()
						.put("orgNo", company.getOrgNo().toString());

				dto.getChildren().add(innerPanel);

				// fill innerOrgs
				List<OrganizationInner> organizationInners = organizationInnerDAO
						.findByCompany(company.getOrgNo());

				if (!organizationInners.isEmpty()) {
					innerPanel.setState("open");
					for (OrganizationInner inner : organizationInners) {

						OrganizationTreeDTO innerData = new OrganizationTreeDTO();
						tree2DTO(inner, innerData);

						innerPanel.getChildren().add(innerData);
					}
				}

				OrganizationTreeDTO servicePanel = new OrganizationTreeDTO();
				LanguageContent languageContent = LanguageContent.getInstance();
				servicePanel.setData(languageContent
						.getContent("OrganizationService.company2dto.Attr"));
				servicePanel
						.getAttr()
						.put("orgName",
								languageContent
										.getContent("OrganizationService.company2dto.Attr"));
				servicePanel.getAttr().put("companyNo",
						company.getOrgNo().toString());
				servicePanel.getAttr().put("orgType", "servicePanel");
				servicePanel.getAttr().put("orgNo",
						company.getOrgNo().toString());
				dto.getChildren().add(servicePanel);

				// 服务部门
				List<OrganizationServices> organizationServices = organizationServicesDAO
						.findByCompany(company.getOrgNo());

				if (!organizationServices.isEmpty()) {
					servicePanel.setState("open");
					for (OrganizationServices ser : organizationServices) {

						OrganizationTreeDTO serData = new OrganizationTreeDTO();
						tree2DTO(ser, serData);
						servicePanel.getChildren().add(serData);
					}
				}
			}

			Set<Organization> suborgs = company.getSuborgs();
			Long[] orgNos = null;
			int i = 0;
			if (suborgs != null && !suborgs.isEmpty()) {
				orgNos = new Long[suborgs.size()];
				for (Organization org : suborgs) {
					orgNos[i] = org.getOrgNo();
					i++;
				}
				Arrays.sort(orgNos);
				for (int s = 0; s < orgNos.length; s++) {
					Company com = companyDAO.findById(orgNos[s]);
					if (com != null) {
						OrganizationTreeDTO subDto = new OrganizationTreeDTO();
						company2dto(com, subDto);
						dto.getChildren().add(subDto);
					}
				}
			}
		} catch (Exception ex) {
			LOGGER.error(ex.getMessage());
		}
	}

	/**
	 * 赋值.
	 * 
	 * @param org
	 * @param dto
	 */
	private void copyValue(Organization org, OrganizationTreeDTO dto) {

		Set<Role> roles = org.getOrgRoles();

		if (roles != null) {
			dto.setOrgRoles(roles);
		}

		dto.setData(org.getOrgName());
		dto.getAttr().put("orgNo", "" + org.getOrgNo());
		dto.getAttr().put("orgName", org.getOrgName());
		dto.getAttr().put("address", org.getAddress());
		dto.getAttr().put("email", org.getEmail());
		dto.getAttr().put("officeFax", org.getOfficeFax());
		dto.getAttr().put("officePhone", org.getOfficePhone());
		dto.getAttr().put("description", org.getDescription());
		dto.getAttr().put("orgType", org.getOrgType());
		// 判断是否在子机构
		List<Organization> orgs = organizationDAO.findSubOrg(org.getOrgNo());
		if (orgs != null && orgs.size() > 0) {
			dto.setState("closed");
		}
		if ("company".equals(org.getOrgType())) {
			dto.setState("open");
		}
		if ("company".equals(org.getOrgType())) {// 公司的一些信息
			Company company = companyDAO.findById(org.getOrgNo());
			dto.getAttr().put("companyNo", company.getOrgNo().toString());
			dto.getAttr().put("homePage", company.getHomePage());
			dto.getAttr().put("logo", company.getLogo());
		}

		// 父机构
		Organization parentOrg = org.getParentOrg();
		if (parentOrg != null) {
			dto.getAttr().put("parentNo", parentOrg.getOrgNo().toString());
		}

		// 负责人
		User personInCharge = org.getPersonInCharge();
		if (personInCharge != null) {
			dto.getAttr().put("personInChargeName",
					personInCharge.getFullName());
			dto.getAttr().put("personInChargeNo",
					personInCharge.getUserId() + "");
		}
	}

	/**
	 * 递归机构.
	 * 
	 * @param org
	 * @param dto
	 */
	public void tree2DTO(Organization org, OrganizationTreeDTO dto) {

		// 赋值
		copyValue(org, dto);

		// 子类
		Set<Organization> suborgs = org.getSuborgs();
		Long[] orgNos = null;
		int i = 0;
		if (suborgs != null && !suborgs.isEmpty()) {
			orgNos = new Long[suborgs.size()];
			dto.setState("closed");
			for (Organization child : suborgs) {
				orgNos[i] = child.getOrgNo();
				i++;
			}
			Arrays.sort(orgNos);
		}
	}

	/**
	 * 查找所有机构
	 */
	@Transactional
	public List<OrganizationDTO> findOrganizationsByType(Long orgNo, String flag) {

		List<OrganizationDTO> orgList = new ArrayList<OrganizationDTO>();

		Organization org = null;

		if (!"ROOT".equals(flag) && orgNo != null) {

			org = organizationDAO.findById(orgNo);

		}

		if ("ROOT".equals(flag)) {// 查找所有机构

			List<Organization> companyList = organizationDAO.findBy("orgType",
					"company");

			if (companyList != null && companyList.size() > 0) {// 所有公司

				for (Organization company : companyList) {
					getByServiceOrgs(orgList, company, "inner,services");
				}
			}

			List<Organization> itsopList = organizationDAO.findBy("orgType",
					"itsop");

			if (itsopList != null && itsopList.size() > 0) {// 所有外包商

				for (Organization itsop : itsopList) {
					getByServiceOrgs(orgList, itsop, "inner,services");
				}
			}

		}else if ("itsop".equals(flag) || "company".equals(flag)) {
			getByServiceOrgs(orgList, org, "inner,services");
		}else if ("service".equals(flag) || "services".equals(flag)) {// 查找服务部门

			getByServiceOrgs(orgList, org, "services");
		}else if ("inner".equals(flag)) {
			// 来这里
			getByServiceOrgs(orgList, org, "inner");
		}else if ("customer".equals(flag)) {
			// 客户
			getByServiceOrgs(orgList, org, "customer");
		}else if ("suppiler".equals(flag)) {
			// 客户
			getByServiceOrgs(orgList, org, "suppiler");
		}else {
			LOGGER.error("查找机构错误");
		}
		return orgList;
	}

	/**
	 * 根据数组id,查找所有机构
	 */
	@Transactional
	public List<OrganizationDTO> findOrganizationsByTypeArray(Long[] orgNo,
			String[] flag) {
		List<OrganizationDTO> orgList = new ArrayList<OrganizationDTO>();
		// List<OrganizationDTO> orgListArray = new
		// ArrayList<OrganizationDTO>();

		Organization org = null;
		int orgLeng = orgNo.length;
		for (int k = 0; k < orgLeng; k++) {
			if ("ROOT".equals(flag[k])) {// 查找所有机构
				List<Organization> companyList = organizationDAO.findBy(
						"orgType", "company");
				if (companyList != null && companyList.size() > 0) {// 所有公司
					for (Organization company : companyList) {
						getByServiceOrgs(orgList, company, "inner,services");
					}
				}

				List<Organization> itsopList = organizationDAO.findBy(
						"orgType", "itsop");
				if (itsopList != null && itsopList.size() > 0) {// 所有外包商
					for (Organization itsop : itsopList) {
						getByServiceOrgs(orgList, itsop, "inner,services");
					}
				}
				// return orgListArray;
			}
			if (!"ROOT".equals(flag[k]) && orgLeng > 0) {

				org = organizationDAO.findById(orgNo[k]);
				if ("itsop".equals(flag[k]) || "company".equals(flag[k])) {
					getByServiceOrgs(orgList, org, "inner,services");
					/*
					 * if(orgList!=null && orgList.size()>0){
					 * for(OrganizationDTO ct:orgList){ OrganizationDTO dto=new
					 * OrganizationDTO(); dto.setOrgName(ct.getOrgName());
					 * dto.setOrgNo(ct.getOrgNo()); orgList.add(dto); } }
					 */
					// return orgList;
				}
				if ("service".equals(flag[k]) || "services".equals(flag[k])) {// 查找服务部门
					getByServiceOrgs(orgList, org, "services");
					/*
					 * if(orgList!=null && orgList.size()>0){
					 * for(OrganizationDTO ct:orgList){ OrganizationDTO dto=new
					 * OrganizationDTO(); dto.setOrgName(ct.getOrgName());
					 * dto.setOrgNo(ct.getOrgNo()); orgList.add(dto); } }
					 */
					// return orgList;
				}
				if ("inner".equals(flag[k])) {
					// 来这里
					getByServiceOrgs(orgList, org, "inner");
					/*
					 * if(orgList!=null && orgList.size()>0){
					 * for(OrganizationDTO ct:orgList){ OrganizationDTO dto=new
					 * OrganizationDTO(); dto.setOrgName(ct.getOrgName());
					 * dto.setOrgNo(ct.getOrgNo()); orgList.add(dto); } }
					 */
					// return orgList;
				}
			}
		}
		return orgList;
	}

	/**
	 * 递归获取被服务部门.
	 * 
	 * @param orgList
	 * @param org
	 * @param filter
	 */
	private void getByServiceOrgs(List<OrganizationDTO> orgList,
			Organization org, String filter) {

		if (org!=null &&!(org.getOrgType() == "company" && filter.equals("inner"))
				&& !(org.getOrgType() == "company" && filter.equals("service"))) {

			// 加入当前机构
			OrganizationDTO pdto = new OrganizationDTO();
			pdto.setOrgNo(org.getOrgNo());
			pdto.setOrgName(org.getOrgName());
			orgList.add(pdto);
		}
		if (org != null && org.getSuborgs() != null) {

			for (Organization c : org.getSuborgs()) {

				if (filter.indexOf(c.getOrgType()) != -1) {

					OrganizationDTO dto = new OrganizationDTO();
					dto.setOrgNo(c.getOrgNo());
					dto.setOrgName(c.getOrgName());
					orgList.add(dto);

					// 递归
					getByServiceOrgs(orgList, c, filter);
				}
			}
		}
	}

	/**
	 * 递归删除子机构
	 */
	private void removeChildrenOrg(Organization org) {

		if (org != null) {

			if (org.getSuborgs() != null && org.getSuborgs().size() > 0) {

				for (Organization o : org.getSuborgs()) {

					removeChildrenOrg(o);
				}
			}else if (org.getOrgType().equals("inner")) {
				organizationInnerDAO.deleteByIds(new Long[] { org.getOrgNo() });
			}else if (org.getOrgType().equals("services")) {
				organizationServicesDAO
						.deleteByIds(new Long[] { org.getOrgNo() });
			}else if (org.getOrgType().equals("company")) {
				companyDAO.deleteByIds(new Long[] { org.getOrgNo() });
				return;
			}else if (org.getOrgType().equals("customer")) {
				customerDAO.deleteByIds(new Long[] { org.getOrgNo() });
			}else if (org.getOrgType().equals("supplier")) {
				customerDAO.deleteByIds(new Long[] { org.getOrgNo() });
			}else if (org.getOrgType().equals("itsop")) {
				throw new ApplicationException("ERROR_DATA_CAN_NOT_DELETE");
			}
		}
	}

	/**
     * 删除服务机构.
     * @param orgNo 机构编号：Long orgNo
     */
	@Transactional
	public void removeServicesOrg(Long orgNo) {

		removeChildrenOrg(organizationDAO.findById(orgNo));
	}

	/**
     * 批量删除机构.
     * @param orgNos 机构编号数组：Long[] orgNos
     */
	@Transactional
	public void deleteOrgs(Long[] orgNos) {

		if (orgNos != null & orgNos.length > 0) {

			for (Long orgNo : orgNos) {
				removeChildrenOrg(organizationDAO.findById(orgNo));
			}
		}

	}

	/**
     * 修改机构.
     * @param dto 机构DTO：OrganizationDTO dto
     */
	@Transactional
	public void updateOrganization(OrganizationDTO dto) {

		Organization entity = organizationDAO.findById(dto.getOrgNo());

		if (dto.getOrgName() != null) {
			entity.setOrgName(dto.getOrgName());
		}

		if (dto.getOfficeFax() != null) {
			entity.setOfficeFax(dto.getOfficeFax());
		}

		if (dto.getOfficePhone() != null) {
			entity.setOfficePhone(dto.getOfficePhone());
		}

		if (dto.getEmail() != null) {
			entity.setEmail(dto.getEmail());
		}

		if (dto.getAddress() != null) {
			entity.setAddress(dto.getAddress());
		}

		organizationDAO.merge(entity);
	}

	/**
     * 修改机构父节构
     * @param dto 机构DTO：OrganizationDTO
     */
	@Transactional
	public void moveOrg(OrganizationDTO dto) {
		Organization entity = organizationDAO.findById(dto.getOrgNo());
		Organization parent = organizationDAO.findById(dto.getParentOrgNo());

		entity.setParentOrg(parent);

		organizationDAO.merge(entity);
		
		if(entity.getParentOrg()!=null){
			entity.setPath(entity.getParentOrg().getPath()+entity.getOrgNo()+"/");
			entity.setPathAlias(entity.getParentOrg().getPathAlias()+entity.getOrgName()+"/");
		}else{
			entity.setPath(entity.getOrgNo()+"/");
			entity.setPathAlias(entity.getOrgName()+"/");
		}
		
	}

	/**
     * 复制机构.
     * @param dto 机构DTO：OrganizationDTO
     */
	@Transactional
	public Long copyOrg(OrganizationDTO dto) {
		Organization source = organizationDAO.findById(dto.getOrgNo());
		Organization parent = organizationDAO.findById(dto.getParentOrgNo());
		Long long1 = null;
		// 内部部门
		if (organizationInnerDAO.findById(dto.getOrgNo()) != null) {
			OrganizationInner entity = new OrganizationInner();

			entity.setParentOrg(parent);
			entity.setOrgName(source.getOrgName());
			entity.setOfficeFax(source.getOfficeFax());
			entity.setOfficePhone(source.getOfficePhone());
			entity.setEmail(source.getEmail());
			entity.setAddress(source.getAddress());

			organizationInnerDAO.save(entity);
			if(entity.getParentOrg()!=null){
				entity.setPath(entity.getParentOrg().getPath()+entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getParentOrg().getPathAlias()+entity.getOrgName()+"/");
			}else{
				entity.setPath(entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getOrgName()+"/");
			}
			long1 = entity.getOrgNo();
		}else if (organizationServicesDAO.findById(dto.getOrgNo()) != null) {// 服务部门
			OrganizationServices entity = new OrganizationServices();

			entity.setParentOrg(parent);
			entity.setOrgName(source.getOrgName());
			entity.setOfficeFax(source.getOfficeFax());
			entity.setOfficePhone(source.getOfficePhone());
			entity.setEmail(source.getEmail());
			entity.setAddress(source.getAddress());

			organizationServicesDAO.save(entity);
			if(entity.getParentOrg()!=null){
				entity.setPath(entity.getParentOrg().getPath()+entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getParentOrg().getPathAlias()+entity.getOrgName()+"/");
			}else{
				entity.setPath(entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getOrgName()+"/");
			}
			long1 = entity.getOrgNo();
		}

		return long1;
	}

	/**
     * 根据机构ID获取对应的角色
     * @param orgNo
     * @return Set<Role>
     */
	@Transactional
	public Set<Role> findRolesById(Long orgNo) {
		Organization org = organizationDAO.findById(orgNo);
		org.getOrgRoles().size();
		Set<Role> roles = org.getOrgRoles();
		return roles;
	}

	/**
     * 导出机构信息.
     * @param qdto
     * @return InputStream
     */
	@Transactional
	public InputStream exportOrganization(OrganizationQueryDTO qdto) {

		if (qdto.getCompanyNo() != null) {// 外包客户视图

			List<Long> subIds = new ArrayList<Long>();

			findAllSubOrganizationByOrganizationNo(subIds, qdto.getCompanyNo());
			Long[] subIdsArr = subIds.toArray(new Long[subIds.size()]);
			qdto.setOrgNos(subIdsArr);
		}

		LanguageContent lc = LanguageContent.getInstance();

		List<String[]> data = new ArrayList<String[]>();
		data.add(new String[] { lc.getContent("common.id"),
				lc.getContent("label.orgSettings.orgType"),
				lc.getContent("label.orgSettings.orgName"),
				lc.getContent("label.orgSettings.orgPhone"),
				lc.getContent("label.orgSettings.orgFax"),
				lc.getContent("label.orgSettings.orgEmail"),
				lc.getContent("label.orgSettings.orgAddress"),
				lc.getContent("label.org.choosePersonInCharge") });// 加入表头

		// 升序排列
		qdto.setSord("asc");
		qdto.setSidx("orgNo");
		PageDTO p = organizationDAO.findPager(qdto);
		List<Organization> entities = (List<Organization>) p.getData();
		String personInChargeNo = "";
		for (Organization org : entities) {
			if (org.getPersonInCharge() != null) {
				personInChargeNo = org.getPersonInCharge().getFullName() + "";
			}
			String orgType = org.getOrgType();
			if (orgType.contains("service"))
				orgType = lc.getContent("label.orgSettings.orgService");
			else if (orgType.contains("inner"))
				orgType = lc.getContent("label.orgSettings.orgInner");
			else if (orgType.contains("company"))
				orgType = lc.getContent("label.report.company");

			data.add(new String[] { org.getOrgNo() + "", orgType,
					org.getOrgName(),
					org.getOfficePhone(), org.getOfficeFax(), org.getEmail(),
					org.getAddress(), personInChargeNo });
		}

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);

		byte[] bs = null;
		try {
			bs = sw.getBuffer().toString().getBytes("GBK");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		ByteArrayInputStream stream = null;
		if(bs!=null){
			stream = new ByteArrayInputStream(bs);
		}
		try {
        	if(csvw!=null){
        		csvw.flush();
    			csvw.close();
        	}
			if(sw!=null){
				sw.flush();
				sw.close();
			}
		} catch (IOException e) {
			LOGGER.error(e);
		}
		return stream;
	}

	/**
     * 导入机构信息.
     * @param importFile
     * @return import result
     */
	@Transactional
	public String importOrganization(String importFile) {
		String result = "failure";
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(new File(importFile));
			Reader rd = new InputStreamReader(new FileInputStream(importFile),
					fileEncode);// 以字节流方式读取数据
			CSVReader reader = new CSVReader(rd);
			String[] line = null;

			int insert = 0;
			int update = 0;
			int total = 0;
			int failure = 0;
			while ((line = reader.readNext()) != null) {

				String orgType = line[1].toString();
				if ("company".equals(orgType)) {// 导入公司信息
					String reluest = importCompanyInfo(line);
					if (reluest == "add") {
						insert++;
					}
					if (reluest == "update") {
						update++;
					}
				}

				else if ("services".equals(orgType)) {
					String reluest = importServicesInfo(line);// 导入服务部门
					if (reluest == "add") {
						insert++;
					}
					if (reluest == "update") {
						update++;
					}
				}

				else if ("inner".equals(orgType)) {// 导入内部部门
					String reluest = importInnerInfo(line);
					if (reluest == "add") {
						insert++;
					}
					if (reluest == "update") {
						update++;
					}
				} else
					failure++;
				total++;
			}
			result = "Total:" + total + ",&nbsp;Insert:" + insert
					+ ",&nbsp;Update:" + update + ",&nbsp;Failure:" + failure;

		} catch (Exception e1) {
			LOGGER.error(e1);
		}
		return result;
	}

	/**
	 * 导入公司信息
	 * @param line
	 * @return String
	 */
	private String importCompanyInfo(String[] line) {
		String result = "";
		Long orgNo = 0L;

		try {
			orgNo = Long.parseLong(line[0].toString());// 机构编号
		} catch (Exception ex) {
			throw new ApplicationException(
					"ERROR_NUMBER_FORMAT_PERSONINCHARGE", ex);
		}
		Company entity = companyDAO.findById(orgNo);
		if (orgNo != 0 && entity == null) {// 导入数据

			Company company = new Company();
			company.setOrgNo(orgNo);
			company.setOrgType(line[1].toString());
			company.setDataFlag(Byte.parseByte(line[2].toString()));
			company.setOrgName(line[3].toString());
			company.setOfficePhone(line[4].toString());
			company.setOfficeFax(line[5].toString());
			company.setEmail(line[6].toString());
			company.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				company.setPersonInCharge(getPersonIncharge(line[8].toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				company.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				company.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}
			if(StringUtils.hasText(line[11])){//公司编号
				company.setCompanyNo(Long.parseLong(line[11]));
			}

			companyDAO.save(company);
			if(company.getParentOrg()!=null){
				company.setPath(company.getParentOrg().getPath()+company.getOrgNo()+"/");
			}else{
				company.setPath(company.getOrgNo()+"/");
			}
			result = "add";
		} else {

			entity.setOrgNo(orgNo);
			entity.setOrgType(line[1].toString());
			entity.setDataFlag(Byte.parseByte(line[2].toString()));
			entity.setOrgName(line[3].toString());
			entity.setOfficePhone(line[4].toString());
			entity.setOfficeFax(line[5].toString());
			entity.setEmail(line[6].toString());
			entity.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				entity.setPersonInCharge(getPersonIncharge(line[8].toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				entity.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				entity.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}
			companyDAO.update(entity);
			if(entity.getParentOrg()!=null){
				entity.setPath(entity.getParentOrg().getPath()+entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getParentOrg().getPathAlias()+entity.getOrgName()+"/");
			}else{
				entity.setPath(entity.getOrgNo()+"/");
				entity.setPathAlias(entity.getOrgName()+"/");
			}
			result = "update";
		}
		return result;
	}

	/**
	 * 导入服务部门.
	 * @param line
	 * @return import result
	 */
	private String importServicesInfo(String[] line) {
		Long orgNo = 0L;
		String result = "";
		try {
			orgNo = Long.parseLong(line[0].toString());// 机构编号
		} catch (Exception ex) {

			throw new ApplicationException("ERROR_NUMBER_FORMAT_SERVICES", ex);
		}

		OrganizationServices org = organizationServicesDAO.findById(orgNo);
		if (orgNo != 0 && org == null) {// 导入数据
			OrganizationServices orgService = new OrganizationServices();
			orgService.setOrgNo(orgNo);
			orgService.setOrgType(line[1].toString());
			orgService.setDataFlag(Byte.parseByte(line[2].toString()));
			orgService.setOrgName(line[3].toString());
			orgService.setOfficePhone(line[4].toString());
			orgService.setOfficeFax(line[5].toString());
			orgService.setEmail(line[6].toString());
			orgService.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				orgService.setPersonInCharge(getPersonIncharge(line[8]
						.toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				orgService.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				orgService.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}
			orgService.setCompanyNo((Long)appctx.getAttribute(SessionName.COMPANYNO.getName()));
			OrganizationServices os = organizationServicesDAO.merge(orgService);

			ServiceTime serviceTime = defaultServiceTime();// 默认服务时间
			serviceTime.setOrganization(os);
			os.setServiceTime(serviceTimeDAO.merge(serviceTime));

			organizationServicesDAO.save(os);
			if(os.getParentOrg()!=null){
				if(os.getParentOrg().getPath()==null)
					os.setPath("1/"+os.getOrgNo()+"/");
				else os.setPath(os.getParentOrg().getPath()+os.getOrgNo()+"/");
			}else{
				os.setPath(os.getOrgNo()+"/");
			}
			String parentOrgName = "";

			if (os.getParentOrg() != null) {
				parentOrgName = "Group_" + os.getParentOrg().getOrgNo();
			}
			ApplicationContext ctx = AppliactionBaseListener.ctx;
			if (ctx != null) {
			IBPS bps = (IBPS) ctx.getBean("bps");
			bps.createGroup("Group_" + os.getOrgNo(), parentOrgName);
			}
			result = "add";

		} else {
			org.setOrgType(line[1].toString());
			org.setDataFlag(Byte.parseByte(line[2].toString()));
			org.setOrgName(line[3].toString());
			org.setOfficePhone(line[4].toString());
			org.setOfficeFax(line[5].toString());
			org.setEmail(line[6].toString());
			org.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				org.setPersonInCharge(getPersonIncharge(line[8].toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				org.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				org.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}
			organizationServicesDAO.update(org);
			if(org.getParentOrg()!=null){
				org.setPath(org.getParentOrg().getPath()+org.getOrgNo()+"/");
			}else{
				org.setPath(org.getOrgNo()+"/");
			}
			result = "update";
		}
		return result;
	}

	/**
	 * 取得默认服务时间.
	 * @return st ServiceTime
	 */
	private ServiceTime defaultServiceTime() {

		ServiceTime st = new ServiceTime();

		st.setAllday(false);// 非全天
		st.setCreateTime(new Date());// 创建时间
		// 周一到周五上班
		st.setMonday(true);
		st.setTuesday(true);
		st.setWednesday(true);
		st.setThursday(true);
		st.setFriday(true);
		st.setSunday(false);
		st.setSaturday(false);
		// 上下班时间
		st.setStartHour(9);
		st.setStartMinute(0);
		st.setEndNoonHour(13);
		st.setEndNoonMinute(0);
		
		st.setStartNoonHour(12);
		st.setStartMinute(0);
		st.setEndHour(17);
		st.setEndMinute(30);
		return st;
	}

	/**
	 * 导入内部部门.
	 * @param line
	 * @return String
	 */
	private String importInnerInfo(String[] line) {
		String result = "";
		Long orgNo = 0L;

		try {
			orgNo = Long.parseLong(line[0].toString());// 机构编号
		} catch (Exception ex) {
			throw new ApplicationException("ERROR_NUMBER_FORMAT_INNER", ex);
		}
		OrganizationInner inn = organizationInnerDAO.findById(orgNo);
		if (orgNo != 0 && inn == null) {// 导入数据

			OrganizationInner inner = new OrganizationInner();

			inner.setOrgNo(orgNo);
			inner.setOrgType(line[1].toString());
			inner.setDataFlag(Byte.parseByte(line[2].toString()));
			inner.setOrgName(line[3].toString());
			inner.setOfficePhone(line[4].toString());
			inner.setOfficeFax(line[5].toString());
			inner.setEmail(line[6].toString());
			inner.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				inner.setPersonInCharge(getPersonIncharge(line[8].toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				inner.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				inner.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}
			inner.setCompanyNo((Long)appctx.getAttribute(SessionName.COMPANYNO.getName()));
			organizationInnerDAO.save(inner);
			if(inner.getParentOrg()!=null){
				inner.setPath(inner.getParentOrg().getPath()+inner.getOrgNo()+"/");
			}else{
				inner.setPath(inner.getOrgNo()+"/");
			}
			result = "add";
		} else {

			inn.setOrgNo(orgNo);
			inn.setOrgType(line[1].toString());
			inn.setDataFlag(Byte.parseByte(line[2].toString()));
			inn.setOrgName(line[3].toString());
			inn.setOfficePhone(line[4].toString());
			inn.setOfficeFax(line[5].toString());
			inn.setEmail(line[6].toString());
			inn.setAddress(line[7].toString());
			if (StringUtils.hasText(line[8])) {
				inn.setPersonInCharge(getPersonIncharge(line[8].toString()));// 负责人
			}
			if (StringUtils.hasText(line[9])) {
				inn.setOrgRoles(getRoles(line[9].toString()));// 机构角色
			}
			if (StringUtils.hasText(line[10])) {
				inn.setParentOrg(getParentOrg(line[10].toString()));// 父节点
			}

			organizationInnerDAO.save(inn);
			if(inn.getParentOrg()!=null){
				inn.setPath(inn.getParentOrg().getPath()+inn.getOrgNo()+"/");
			}else{
				inn.setPath(inn.getOrgNo()+"/");
			}
			result = "update";
		}
		return result;
	}

	/**
	 * 获取负责人
	 * @param personInChargeNoStr
	 * @return User
	 */
	private User getPersonIncharge(String personInChargeNoStr) {

		// 负责人.
		try {

			Long personInChargeNo = Long.parseLong(personInChargeNoStr);// 负责人

			try {
				return userDAO.findById(personInChargeNo);

			} catch (NullPointerException ex) {// 未找到用户

				throw new ApplicationException(
						"ERROR_PERSONINCHARGE_UNDEFINED", ex);
			}

		} catch (NumberFormatException ex) {// 数字转换错误.
			throw new ApplicationException(
					"ERROR_NUMBER_FORMAT_PERSONINCHARGE", ex);
		}

	}

	/**
	 * 根据字符串取得角色列表.
	 * @param orgRolesNoStr
	 * @return Set<Role>
	 */
	@SuppressWarnings("rawtypes")
	private Set<Role> getRoles(String orgRolesNoStr) {
		Set<Role> roles = null;
		if (StringUtils.hasText(orgRolesNoStr)) {

			String[] arr = orgRolesNoStr.split(",");
			roles = new HashSet();

			for (String r : arr) {
				if (!r.equals("")) {

					roles.add(roleDAO.findById(Long.parseLong(r)));
				}
			}
		} 
		return roles;
	}

	/**
	 * 获取父机构信息
	 * @param parentOrgNoStr
	 * @return Organization
	 */
	private Organization getParentOrg(String parentOrgNoStr) {

		try {

			Long parentOrgNo = Long.parseLong(parentOrgNoStr);// 父节点

			try {
				return organizationDAO.findById(parentOrgNo);

			} catch (NullPointerException ex) {// 未找到用户

				throw new ApplicationException("ERROR_PARENTORG_UNDEFINED", ex);
			}

		} catch (NumberFormatException ex) {// 数字转换错误.
			throw new ApplicationException("ERROR_NUMBER_FORMAT_PARENTORG", ex);
		}

	}

	/**
	 * 获取外包服务商公司
	 * @return OrganizationDTO
	 */
	public OrganizationDTO findServiceProvidersCompany() {
		Organization org = organizationDAO.findTopCompany();
		OrganizationDTO orgDTO = new OrganizationDTO();
		if(org!=null){
			orgDTO.setOrgName(org.getOrgName());
			orgDTO.setOrgNo(org.getOrgNo());
		}
		return orgDTO;
	}

	/**
	 * 查父机构
	 * @param orgNo
	 * @param orgSets
	 */
	private void findParentOrg(Long orgNo, Set<Long> orgSets) {
		if(orgNo !=null ){
			Organization org = organizationDAO.findById(orgNo);
			orgSets.add(orgNo);
			if (org != null && org.getParentOrg() != null) {
				findParentOrg(org.getParentOrg().getOrgNo(), orgSets);
			}
		}
	}

	/**
	 * 反转查找机构，也就是反方向把其父机构一起查找出来
	 * @param orgNos
	 * @return Long[]
	 */
	public Long[] reverFindOrg(Long[] orgNos) {
		Set<Long> orgSets = new HashSet<Long>();
		for (Long orgNo : orgNos) {
			findParentOrg(orgNo, orgSets);
		}
		Long[] orgs = (Long[]) orgSets.toArray(new Long[orgSets.size()]);
		return orgs;
	}

	/**
	 * 根据用户获取机构负责人
	 * @param userId 用户ID
	 * @param level 取当前、取上一个、取上上个机构....的负责人(取当前用户机构负责人为0，上一个为1，依次类推)
	 * @return 返回机构负责人
	 */
	public User findOrganizationOwnerByUser(Long userId , Long level){
		
		User user = userDAO.findById(userId);
		Organization org = user.getOrgnization();
		if(level==null || level==0L){
			if(org!=null){
				return org.getPersonInCharge();
			}else{
				return null;
			}
		}else if(level>0){
			for(int i = 0 ; i<level ; i++){
				org = findParentOrg(org);
				if(org==null){
					break;
				}
			}
		}
		if(org!=null){
			return org.getPersonInCharge();
		}else{
			return null;
		}
	}
	private Organization findParentOrg(Organization org){
		if(org!=null){
			return org.getParentOrg();
		}else{
			return null;
		}
		
	}
	
	/**
	 * 根据用户名查询机构
	 * @param loginName
	 * @return map
	 */
	@SuppressWarnings("rawtypes")
    public Map findOrgGroupHeadsByname(String loginName) {
		Map map = new HashMap();
		int n = 0;
		User user = userDAO.findUserByLoginName(loginName);
		Organization org = user.getOrgnization();
		map = findOrgByChild(org.getOrgNo(), map, n);
		return map;
	}

	/**
     * 遍历机构负责人
     * @param orgNo
     * @param map
     * @param n 层次
     * @return Map
     */
	@SuppressWarnings("rawtypes")
    public Map findOrgByChild(Long orgNo, Map map, int n) {
		if (orgNo != null) {
			Organization org = organizationDAO.findById(orgNo);
			if (org.getPersonInCharge() != null) {
				map.put("leader_" + n, org.getPersonInCharge().getUserId());
				n++;
				if (org.getParentOrg() != null) {
					findOrgByChild(org.getParentOrg().getOrgNo(), map, n);
				}
			}
		}
		return map;
	}
	/**
     * 根据机构名称查询
     * @param orgName
     * @return Organization
     */
	@Transactional
	public Organization findOrgByName(String orgName){
		Organization org = null;
		List<Organization> orgs = organizationDAO.findOrgByName(orgName);
		if(orgs!=null && orgs.size()>0){
			org = orgs.get(0);
		}
		return org;
	}
	/**
     * 根据机构名称和父节点名称查询
     * @param orgName
     * @return Organization
     */
	@Transactional
	public Organization findOrgByOrgNameOrparentOrgName(String orgName,String parentOrgName){
		Organization org = null;
		List<Organization> orgs = organizationDAO.findOrgByOrgNameOrparentOrgName(orgName,parentOrgName);
		if(orgs!=null && orgs.size()>0){
			org = orgs.get(0);
		}
		return org;
	}
	/**
	 * 根据编号获得角色列表
	 */
	@Transactional
	public List<Long> findRolesByOrgNo(Long orgNo){
		List<Long> orgRoles = null;
		if (orgNo != null) {
			Set<Role> entitys = findRolesById(orgNo);
			List<Long> roleIds = new ArrayList<Long>();
			// add mars 20110608
			if (entitys != null) {
				for (Role r : entitys) {
					roleIds.add(r.getRoleId());
				}
			}
			orgRoles = roleIds;
		}
		return orgRoles;
	}
	
	/**
     * 判断分类是否存在
     * @param ec
     */
    public boolean isCategoryExisted(OrganizationDTO dto) {
    	if(dto.getOrgNo()!=null){
    		Organization organization = organizationDAO.findById(dto.getOrgNo());
        	if(organization!=null){
        		if (dto.getParentOrgNo() == null && organization.getParentOrg() != null) {
                    dto.setParentOrgNo(organization.getParentOrg().getOrgNo());
                }
                if (dto.getOrgName() == null) {
                    dto.setOrgName(organization.getOrgName());
                }
                if(dto.getOrgType()==null){
                	dto.setOrgType(organization.getOrgType());
                }
        	}
    	}
        return organizationDAO.isCategoryExisted(dto);
    }
    
    /**
     * 判断编辑时分类是否存在
     * @param dto
     * @return
     */
    public boolean isCategoryExistdOnEdit(OrganizationDTO dto) {
        boolean flag = true;
        Organization organization = null;
        if(dto.getOrgNo()!=null){
        	organization = organizationDAO.findById(dto.getOrgNo());
        }
        if (organization != null && organization.getOrgName().equals(dto.getOrgName())){
        	flag = false;
        }else {
        	flag = this.isCategoryExisted(dto);
        }
        return flag;
    }
    /**
     * 根据上传图片名称获取LOGO图片流
     * @param companyNo
     * @return InputStream
     */
	public InputStream getImageUrlforimageStream(String actionType) {
		InputStream imageStream = null;
		String filePath =AppConfigUtils.getInstance().getFileManagementPath()+actionType+"/jasper/logo.jpg";
		File file = new File(filePath);
		try {
			imageStream = new FileInputStream(file);
		} catch (Exception e) {
			throw new ApplicationException("ERROR_ATTACHMENT_FAIL_READ\n", e.getMessage());
		}
		return imageStream;
	}
}
